package com.shark.stock.model
{
	import com.asfusion.mate.core.EventMap;
	import com.shark.stock.events.SecurityEvent;
	import com.shark.stock.events.StockEvent;
	import com.shark.stock.vos.Article;
	import com.shark.stock.vos.User;
	
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.SharedObject;
	
	import flashx.textLayout.formats.Float;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.rpc.Fault;
	import mx.states.State;

	public class SharkManager extends EventDispatcher
	{
		[Bindable]
		public var applicationState:String = StockConstants.NOT_LOGGED;
		
		[Bindable]
		public var user:User;
		
		[Bindable]
		public var stock:ArrayCollection;
		
		[Bindable]
		public var article:Article;
		
		[Bindable]
		public var categories:ArrayCollection;
		
		private var dispatcher:IEventDispatcher; 
		
		private var so:SharedObject;
		
		public function SharkManager( dispatcher:IEventDispatcher )
		{
			super();
			this.dispatcher = dispatcher;
			so = SharedObject.getLocal("shark");
		}
		
		public function showError(fault:Fault,user:User):void{
			Alert.show("Error:" + fault.faultString);
		}
		
		public function prepareLogin():void{
			user = new User();
			if(so.data.user && so.data.user.name != undefined){
				user.name = so.data.user.name;
				user.pass = so.data.user.pass;
			}
		}
		
		public function setCategories(resultObject:ArrayCollection):void{
			categories = resultObject;
		}
		
		public function prepareNewArticle():void{
			article = new Article();
			article.name="Enter name here....";
			article.price=0;
		}
		
		public function prepareEditArticle(article:Article):void{
			this.article = article;
		}
		
		public function saveArticle(article:Article):void{
			trace("article locally saved");
			if(article.id==0){
				article.id = stock.length+1;
				stock.addItem(article);
				
				// PORQUE? stock.setItemAt(article,stock.getItemIndex(article));
				// Para guardar la edición de un artículo, pero se guarda solo :|
			}
				
		}
		
		public function setStock(resultObject:ArrayCollection):void{
			stock = resultObject;
		}
		
		public function login( user:User, loginResult:Boolean ):void
		{
			if( loginResult )
			{	
				applicationState = StockConstants.LOGGED;
				this.user = user;
				dispatcher.dispatchEvent( new SecurityEvent( SecurityEvent.LOGIN_SUCCESS ) );
			} else {
				Alert.show("usuario incorrecto...");
			}
		}
		
		public function logout():void
		{
			Alert.show("Do you want to save your user?","Good Bye!",Alert.YES | Alert.NO, null,this.persistUser);
			
		}
		
		private function persistUser(event:CloseEvent):void{
			if(event.detail == Alert.YES){
				so.data.user = user;
				so.flush(500);
			}else{
				so.clear();
			}
			applicationState = StockConstants.NOT_LOGGED;
		}
	}
}